import * as vscode from 'vscode';
import { TreeItem } from 'vscode';
export const uiCommands = [
    {
        "command": "diyextapi.apistart",
        "title": "Api Start"
    },
    {
        "command": "diyextapi.show_info",
        "title": "Api[showInformationMessage]"
    },
    {
        "command": "diyextapi.show_error",
        "title": "Api[showErrorMessage]"
    },
    {
        "command": "diyextapi.show_warning",
        "title": "Api[showWarningMessage]"
    },
    {
        "command": "diyextapi.show_info_item",
        "title": "Api[showErrorMessage.item]"
    },
    {
        "command": "diyextapi.show_input_box",
        "title": "Api[showInputBox]"
    },
    {
        "command": "diyextapi.input_box_option",
        "title": "Api[InputBoxOption]"
    },
    {
        "command": "diyextapi.input_box_callback",
        "title": "Api[InputBoxCallback]"
    },
    {
        "command": "diyextapi.open_dialog",
        "title": "Api[showOpenDialog]"
    },
    {
        "command": "diyextapi.open_dialog_option",
        "title": "Api[showOpenDialogOption]"
    },
    {
        "command": "diyextapi.open_dialog_callback",
        "title": "Api[showOpenDialogCallback]"
    },
    {
        "command": "diyextapi.save_dialog",
        "title": "Api[showSaveDialog]"
    },
    {
        "command": "diyextapi.save_dialog_option",
        "title": "Api[showSaveDialogOption]"
    },
    {
        "command": "diyextapi.save_dialog_callback",
        "title": "Api[showSaveDialogCallback]"
    },
    {
        "command": "diyextapi.quick_pick",
        "title": "Api[showQuickPick]"
    },
    {
        "command": "diyextapi.quick_pick_option",
        "title": "Api[showQuickPickOption]"
    },
    {
        "command": "diyextapi.quick_pick_callback",
        "title": "Api[showQuickPickCallback]"
    },
    {
        "command": "diyextapi.show_text_document",
        "title": "Api[showTextDocument]"
    }, 
    {
        "command": "diyextapi.open_text_document",
        "title": "Api[openTextDocument]"
    },
    {
        "command": "diyextapi.showWorkspaceFolderPick",
        "title": "Api[showWorkspaceFolderPick]"
    },
    {
        "command": "diyextapi.showWorkspaceFolderPickOption",
        "title": "Api[showWorkspaceFolderPickOption]"
    },
    {
        "command": "diyextapi.showWorkspaceFolderPickCallback",
        "title": "Api[showWorkspaceFolderPickCallback]"
    },
    {
        "command": "diyextapi.withProgress",
        "title": "Api[withProgress]"
    },
    {
        "command": "diyextapi.createOutputChannel",
        "title": "Api[createOutputChannel]"
    },
    {
        "command": "diyextapi.outputChannel.Append",
        "title": "Api[outputChannel.Append]"
    },
    {
        "command": "diyextapi.outputChannel.appendLine",
        "title": "Api[outputChannel.appendLine]"
    },
    {
        "command": "diyextapi.createWebviewPanel",
        "title": "Api[createWebviewPanel]"
    },
    {
        "command": "diyextapi.setStatusBarMessage",
        "title": "Api[setStatusBarMessage]"
    },
    {
        "command": "diyextapi.createStatusBarItem",
        "title": "Api[createStatusBarItem]"
    },
    {
        "command": "diyextapi.createTerminal",
        "title": "Api[createTerminal]"
    },
    {
        "command": "diyextapi.createTreeView",
        "title": "Api[createTreeView]"
    },
    {
        "command": "diyextapi.createTreeViewChildren",
        "title": "Api[createTreeView.Children]"
    },
    {
        "command": "diyextapi.createTreeViewJson",
        "title": "Api[createTreeView.Json]"
    },
    {
        "command": "diyextapi.createTreeViewApi",
        "title": "Api[createTreeView.Api]"
    }
]

export const uiCommandsCb = [
    () => {
        vscode.window.showInformationMessage("apiSstart");
    },
    () => {
        vscode.window.showInformationMessage("info msg");
    },
    () => {
        vscode.window.showErrorMessage("error msg");
    },
    () => {
        vscode.window.showWarningMessage("warning msg");
    },
    () => {
        vscode.window.showInformationMessage("info msg", "info item1", "info item2").then((input) => {
            vscode.window.showInformationMessage("info msg:用户输入" + input);
        });
    },
    () => {
        vscode.window.showInputBox();
    },
    () => {
        vscode.window.showInputBox({
            value: "inputValue",
            valueSelection: [1, 3], //默认选择value部分内容
            prompt: "promt", //操作提示语
            placeHolder: "placeHolder",
            // password:true,
        });
    },
    () => {
        vscode.window.showInputBox().then((input) => {
            vscode.window.showInformationMessage("用户输入" + input);
        });
    },
    () => {
        // 打开选择文件夹 Open.Select
        vscode.window.showOpenDialog();
    },
    () => {
        // 打开选择文件夹的选项
        vscode.window.showOpenDialog({
            openLabel: "openLabel", //右下角选择文件确认按钮
            canSelectFiles: true, //可以选择文件
            canSelectFolders: false, //只选择目录
            canSelectMany: false,   //可以选择多个
            filters: { "TypeScript": ['ts', "tsx"] }, //选择特定后缀
            title: "title" //左上角标题
        });
    },
    () => {
        vscode.window.showOpenDialog({
            canSelectMany: true,
        }).then((checkFiles) => {
            let files = checkFiles?.map(d => d.fsPath);
            vscode.window.showInformationMessage("用户选择的文件", ...files || []);
        });
    },
    () => {
        // 创建文件后的保存New,Save
        vscode.window.showSaveDialog();
    },
    () => {
        vscode.window.showSaveDialog({
            saveLabel: "saveLabel",
            filters: { "ts": ["ts"] },
            title: "title"
        });
    },
    () => {
        vscode.window.showSaveDialog().then((saveFiles) => {
            vscode.window.showInformationMessage("用户选择的文件", saveFiles?.fsPath || "");
        });
    },
    () => {
        // 下拉列表
        vscode.window.showQuickPick([
            "quickPick1",
            "quickPick2",
            "quickPick3"
        ]);
    },
    () => {
        vscode.window.showQuickPick(
            [
                "quickPickOption1",
                "quickPickOption2",
                "quickPickOption3"
            ],
            {
                placeHolder: "placeHolder",
                canPickMany: true,

                onDidSelectItem: item => {
                    vscode.window.showInformationMessage(
                        "quickPick",
                        JSON.stringify(item));
                }
            }
        );
    },
    () => {
        vscode.window.showQuickPick(
            [
                "quickPickCallback1",
                "quickPickCallback2",
                "quickPickCallback3"
            ],
            {
                placeHolder: "placeHolder",
                canPickMany: true,

                onDidSelectItem: item => {
                    vscode.window.showInformationMessage(
                        "quickPickCallback1",
                        JSON.stringify(item));
                }
            }
        ).then((picks) => {
            vscode.window.showInformationMessage("quick回调", ...picks || []);
        });
    },
    () => {
        // openTextDocument默认打开一个新建文件
        vscode.workspace.openTextDocument().then((doc) => {
            //  showTextDocument
            vscode.window.showTextDocument(doc);
        })
    },
    () => {
        // openTextDocument默认打开一个新建文件
        vscode.workspace.openTextDocument({
            language: "lua",
            content: "local a = 1"
        }).then((doc) => {
            //  showTextDocument
            vscode.window.showTextDocument(doc);
        })
    },
    () => {
        vscode.window.showWorkspaceFolderPick();
    },
    () => {
        vscode.window.showWorkspaceFolderPick({
            placeHolder:"placeHolder"
        });
    },
    () => {
        vscode.window.showWorkspaceFolderPick().then((folder)=>{
            let folderName = [folder?.name || "noFolderName",folder?.uri.fsPath || "noFolderPath"] 

            vscode.window.showInformationMessage("showWorkspaceFolderPick",
             ...folderName);
        });
    },
    () => {
        vscode.window.withProgress({
            location: vscode.ProgressLocation.Notification,
            title: "I am long running!",
            cancellable: true
        }, (progress, token) => {
            token.onCancellationRequested(() => {
                console.log("User canceled the long running operation");
            });

            progress.report({ increment: 0 });

            setTimeout(() => {
                progress.report({ increment: 10, message: "I am long running! - still going..." });
            }, 1000);

            setTimeout(() => {
                progress.report({ increment: 40, message: "I am long running! - still going even more..." });
            }, 2000);

            setTimeout(() => {
                progress.report({ increment: 50, message: "I am long running! - almost there..." });
            }, 3000);

            const p = new Promise<void>(resolve => {
                setTimeout(() => {
                    resolve();
                }, 5000);
            });

            return p;
        });
    },
    () => {
        // 控制台输出内容
        vscode.window
        .createOutputChannel("outPutChannel")
        .show();
    },
    () => {
        // 控制台输出内容
        let out = vscode.window
        .createOutputChannel("outPutChannel");
        out.append("output");
        out.append("output");
        out.append("output");
        out.show();
    },
    () => {
        // 控制台输出内容
        let out = vscode.window
        .createOutputChannel("outPutChannel");
        out.appendLine("appendLine")
        out.appendLine("appendLine")
        out.appendLine("appendLine")
        out.show();
    },
    () => {
        let webv = vscode.window.createWebviewPanel(
            "webview",
            "webView",
            vscode.ViewColumn.Active
        )
        webv.webview.html = `
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>HelloWebview</title>
            </head>
            <body>
                <div>Hello Webview</div>
            </body>
            </html>
        `;
    },
    () => {
        vscode.window.setStatusBarMessage(
            "setStatusBarMessage"
        )
    },
    () => {
        let statusItem = vscode.window.createStatusBarItem()
        statusItem.text = "createStatusBarItem";
        statusItem.text = "tooltip";
        statusItem.color = "#gray";
        statusItem.show();
    },
    () => {
        // 打开一个控制台
        vscode.window.createTerminal(
            "terminal",
        ).show();
    },
    () => {
        // TreeView
        /**
         * apiTree 对应package.json中注册的
         * name    对应侧边栏的label
         * "contributes": {
                ....
                "views": {
                    "explorer": [
                        {
                            "id": "testView",
                            "name": "vscode的api展示"
                        }
                    ]
                },
                ...
            }
         * 
         */
        vscode.window.createTreeView("apiTree",{
            treeDataProvider:{
                getTreeItem:function(){
                    return new TreeItem(
                        ""
                    )
                },
                getChildren:function(){
                    return []
                }
            }
        })
    },
    () => {
        // TreeView
        // getChildren() 获取子节点列表
        // getTreeItem() 获取节点配置
        vscode.window.createTreeView("apiTree",{
            treeDataProvider:{
                // 节点配置(label,是否可展开) 
                // 节点的配置项
                // treeInput父级节点名称
                getTreeItem:function(treeInput:string){
                    return new TreeItem(
                        "TreeItem_"+treeInput,
                        vscode.TreeItemCollapsibleState.Collapsed
                    )
                },
                // 获取子节点 
                // 决定子节点的数量
                // key 上级节点名称 
                getChildren:function(key){
                    return  key 
                        ? ["children1","children2",key]
                        : ["根节点1","根节点2"]
                    }
            }
        })
    },
    () => {
        // TreeView
        // json结构需要把key设置为唯一id
        let jsonTree = {
            "根节点1":{
                "子节点11":{
                    "子节点111":{
                        "子节点1111":{

                        }
                    }
                }
            },
            "根节点2":{
                "子节点21":{
                    "子节点211":{
                        "子节点2111":{
                        
                        }
                    }
                },
                "子节点22":{
                    "子节点221":{
                        "子节点222":{
                        
                        }
                    }
                },
            },
            "根节点3":{
                "子节点31":{
                    "子节点311":{
                        "子节点311":{
                        
                        }
                    }
                },
                "子节点32":{
                    "子节点321":{
                        "子节点3211":{
                        
                        }
                    }
                },
                "子节点33":{
                    "子节点331":{
                        "子节点3331":{
                        
                        }
                    }
                }
            }
        }

        function getChildren(key:string|undefined): string[] {
            // 根节点
            if (!key) {
                return Object.keys(jsonTree);
            }
            // 获取key对应的子节点
            const treeElement = getTreeElement(key,jsonTree);
            if (treeElement) {
                return treeElement;
            }
            return [];
        }
        function getTreeElement(key:string,parent:any): any {
            if (!key) {
                return [];
            }
            let checkKeyIndex = Object.keys(parent).indexOf(key);
            if(checkKeyIndex > -1){
                return Object.keys(parent[key]);
            }
            for(let i = 0; i < Object.keys(parent).length;i++){
                let treeResult =  getTreeElement(key,parent[Object.keys(parent)[i]]);
                if(treeResult.length > 0){
                    return treeResult;
                }
            }
            return [];
        }
        function getTreeItem(key: string): vscode.TreeItem {
            return {
                label: key,
                tooltip: `鼠标悬浮提示 ${key}`,
                collapsibleState: vscode.TreeItemCollapsibleState.Collapsed 
            };
        }

        vscode.window.createTreeView("apiTree",{
            treeDataProvider:{
                // 节点配置(label,是否可展开) 
                // 节点的配置项
                getTreeItem:function(key:string){
                    return getTreeItem(key);
                },
                // 获取子节点 
                // 决定子节点的数量
                getChildren:function(key:string | undefined){
                    console.log("key----",key);
                    return getChildren(key);
                }
            }
        })
    },
    () => {

        function getChildren(item:element|undefined): element[] {
            // 根节点
            if (!item) {
                let mNames = require("../src/api/moduleNames.json") as string[];
                return mNames.map(m => mapToItem(m,"module"));
            }
            if(item.type == "module"){
                let classNames = require("../src/api/classNames.json") as classEl[];
                console.log("cls",classNames);

                let mClass = classNames
                .filter(c =>c.module == item.name)
                .map(c => mapToItem(c.name,"class"));

                return mClass;
            }

            if(item.type == "class"){

            }
            return [];
        }
        function mapToItem(name:string,type:elementType):element{
            return {
                name,
                type
            }
        }
       
        function getTreeItem(item:element): vscode.TreeItem {
            return {
                label: item.name,
                tooltip: `鼠标悬浮提示 ${item.name}`,
                collapsibleState: vscode.TreeItemCollapsibleState.Collapsed 
            };
        }

        vscode.window.createTreeView("apiTree",{
            treeDataProvider:{
                // 节点配置(label,是否可展开) 
                // 节点的配置项
                getTreeItem:function(key:element){
                    return getTreeItem(key);
                },
                // 获取子节点 
                // 决定子节点的数量
                getChildren:function(key:element | undefined){
                    console.log("key----",key);
                    return getChildren(key);
                }
            }
        })
    }
];

type elementType = "module" | "function" | "class" | "method" | "property"
type element = {
    type:elementType
    name:string,
}
type classEl = {
    "module": string,
    "name": string,
    "pos": number,
    "end": number
}